package com.zs.letcode.tencent;

/**
 * 螺旋矩阵 II
 * 给你一个正整数n ，生成一个包含 1 到n2所有元素，且元素按顺时针顺序螺旋排列的n x n 正方形矩阵 matrix 。
 * <p>
 *
 * <p>
 * 示例 1：
 * <p>
 * <p>
 * 输入：n = 3
 * 输出：[[1,2,3],[8,9,4],[7,6,5]]
 * 示例 2：
 * <p>
 * 输入：n = 1
 * 输出：[[1]]
 *
 * <p>
 * 提示：
 * <p>
 * 1 <= n <= 20
 * 相关标签
 * 数组
 * 矩阵
 * 模拟
 * <p>
 * 作者：力扣 (LeetCode)
 * 链接：https://leetcode-cn.com/leetbook/read/tencent/x5rn92/
 * 来源：力扣（LeetCode）
 * 著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
 *
 * @author madison
 * @description
 * @date 2021/7/13 08:40
 */
public class Chapter17 {
    public static void main(String[] args) {

    }

    private static class Solution {
        /**
         * 方法一：模拟
         */
        public int[][] generateMatrix(int n) {
            int maxNum = n * n;
            int curNum = 1;
            int[][] matrix = new int[n][n];
            int row = 0, column = 0;
            int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};// 右下左上
            int directionIndex = 0;
            while (curNum <= maxNum) {
                matrix[row][column] = curNum;
                curNum++;
                int nextRow = row + directions[directionIndex][0];
                int nextColumn = column + directions[directionIndex][1];
                if (nextRow < 0 || nextRow >= n || nextColumn < 0 || nextColumn >= n || matrix[nextRow][nextColumn] != 0) {
                    directionIndex = (directionIndex + 1) % 4; // 顺时针旋转至下一个方向
                }
                row = row + directions[directionIndex][0];
                column = column + directions[directionIndex][1];
            }
            return matrix;
        }

        /**
         * 方法二：按层模拟
         */
        public int[][] generateMatrix1(int n) {
            int num = 1;
            int[][] matrix = new int[n][n];
            int left = 0, right = n - 1, top = 0, bottom = n - 1;
            while (left <= right && top <= bottom) {
                for (int column = left; column <= right; column++) {
                    matrix[top][column] = num;
                    num++;
                }
                for (int row = top + 1; row <= bottom; row++) {
                    matrix[row][right] = num;
                    num++;
                }
                if (left < right && top < bottom) {
                    for (int column = right - 1; column > left; column--) {
                        matrix[bottom][column] = num;
                    }
                    for (int row = bottom; row > top; row--) {
                        matrix[row][left] = num;
                        num++;
                    }
                }
                left++;
                right--;
                top++;
                bottom--;
            }
            return matrix;
        }
    }
}
